package io.github.mosiki.modules.job.service.impl;

import io.github.mosiki.common.utils.Constant;
import io.github.mosiki.modules.job.converter.ScheduleJobConverter;
import io.github.mosiki.modules.job.domain.ScheduleJob;
import io.github.mosiki.modules.job.dto.ScheduleJobDTO;
import io.github.mosiki.modules.job.repository.ScheduleJobRepository;
import io.github.mosiki.modules.job.service.ScheduleJobService;
import io.github.mosiki.modules.job.utils.ScheduleUtils;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;


/**
 * 类名称：ScheduleJobServiceImpl
 * 类描述：定时任务
 * 创建人：WeJan
 * 创建时间：2018-07-21 13:20:39
 */
@Service("scheduleJobService")
public class ScheduleJobServiceImpl implements ScheduleJobService {
    @Autowired
    private ScheduleJobRepository scheduleJobRepository;
    @Autowired
    private Scheduler scheduler;

    /**
     * 项目启动时，初始化定时器
     */
    @PostConstruct
    public void init(){
        List<ScheduleJobDTO> scheduleJobList = ScheduleJobConverter.conver(scheduleJobRepository.findAll());
        for(ScheduleJobDTO scheduleJob : scheduleJobList){
            CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, scheduleJob.getJobId());
            //如果不存在，则创建
            if(cronTrigger == null) {
                ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
            }else {
                ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);
            }
        }
    }

    @Override
    public Page<ScheduleJobDTO> listScheduleJob(Map<String, Object> params, PageRequest pageRequest) {
        //TODO 参数没用上 动态查询
        Page<ScheduleJob> all = scheduleJobRepository.findAll(pageRequest);
        List<ScheduleJobDTO> dtos = ScheduleJobConverter.conver(all.getContent());
        return new PageImpl<>(dtos, pageRequest, all.getTotalElements());
    }

    @Override
    public ScheduleJobDTO findById(Long jobId) {
        return ScheduleJobConverter.conver(scheduleJobRepository.findById(jobId).orElse(null));
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ScheduleJob saveScheduleJob(ScheduleJobDTO scheduleJobDTO) {
        scheduleJobDTO.setStatus(Constant.STATUS_OK);
        ScheduleJob scheduleJob = scheduleJobRepository.save(ScheduleJobConverter.conver(scheduleJobDTO));
        ScheduleUtils.updateScheduleJob(scheduler, ScheduleJobConverter.conver(scheduleJob));
        return scheduleJob;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ScheduleJob updateScheduleJob(ScheduleJobDTO scheduleJob) {
        ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);
        return scheduleJobRepository.save(ScheduleJobConverter.conver(scheduleJob));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteBatchIds(List<Long> jobIds) {
        // TODO
//        jobIds.forEach(e -> );
//        ScheduleUtils.deleteScheduleJob()
        return scheduleJobRepository.deleteByJobIdIn(jobIds);
    }

    @Override
    public int updateBatch(Long[] jobIds, int status) {
        return scheduleJobRepository.updateBatch(jobIds, status);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void run(Long[] jobIds) {
        for (Long jobId : jobIds) {
            ScheduleUtils.run(scheduler, this.findById(jobId));
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void pause(Long[] jobIds) {
        for (Long jobId : jobIds) {
            ScheduleUtils.pauseJob(scheduler, jobId);
        }

        updateBatch(jobIds, Constant.ScheduleStatus.PAUSE.getValue());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resume(Long[] jobIds) {
        for (Long jobId : jobIds) {
            ScheduleUtils.resumeJob(scheduler, jobId);
        }

        updateBatch(jobIds, Constant.ScheduleStatus.NORMAL.getValue());
    }
}
